const { ccclass, property } = cc._decorator;
import DetailsManager from './DetailsManager';
import WinFormBase from '../WinFormBase';
import hitMsgControl from '../Lobby/hitMsgControl';

@ccclass
export default class SetName extends cc.Component {
    @property(cc.Label)
    nameLabel: cc.Label = null;
    @property(cc.Node)
    writeBox: cc.Node = null;
    @property(cc.Button)
    writebutton: cc.Button = null;
    @property(cc.Node)
    DetailsNode: cc.Node = null;
    @property(cc.Node)
    msgForm: cc.Node = null;

    _isWrite: boolean = false;
    _name: string = "";

    _DetailsManager: DetailsManager = null;
    onLoad() {
        this.writeBox.active = false;
        this._DetailsManager = this.DetailsNode.getComponent(DetailsManager);
    }
    /**
     * 开始编辑
     */
    writeClick() {
        if (this._isWrite) {
            this.endEdit();
        }
        else {
            this.beginEdit();
        }
    }
    /**
     * 结束编辑
     */
    endWrit() {
        let nameWrite = this.writeBox.getComponent(cc.EditBox).string;
        if (nameWrite)
            this.checkWrite(nameWrite.trim());
    }
    /**
    * 结束编辑
    */
    returnWrit() {
        let nameWrite = this.writeBox.getComponent(cc.EditBox).string;
        if (nameWrite)
            this.checkWrite(nameWrite.trim());
    }
    checkWrite(nameWrite: string) {
        if (nameWrite == this._name || nameWrite.length == 0) {
            return;
        }
        if (this.chkstrlen(nameWrite) > 12) {
            let control = this.msgForm.getComponent(hitMsgControl)
            control.lebelNode.string = "输入长度不能超出12，1个汉字长度为2。";
            let formNode = new cc.Node();
            let formControl = formNode.addComponent(WinFormBase);
            formControl.mainNode = this.msgForm;
            this.node.addChild(formNode);
        }
        else {
            this.nameLabel.string = nameWrite;
            this._name = nameWrite;
            this._DetailsManager.reName(nameWrite);
            this.endEdit();
        }
    }
    private beginEdit() {
        this.writeBox.active = true;
        this._isWrite = true;
    }
    private endEdit() {
        this.writeBox.active = false;
        this._isWrite = false;
    }
    //判断字符串长度
    chkstrlen(str: string): number {
        var strlen = 0;
        for (var i = 0; i < str.length; i++) {
            if (str.charCodeAt(i) > 255) //如果是汉字，则字符串长度加2
                strlen += 2;
            else
                strlen++;
        }
        return strlen;
    }
}
